package com.zky.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zky.common.constant.AuthServerConstant;
import com.zky.common.utils.R;
import com.zky.common.vo.MemberRespVo;
import com.zky.gulimall.product.entity.SkuImagesEntity;
import com.zky.gulimall.product.entity.SpuInfoDescEntity;
import com.zky.gulimall.product.feign.SecKillFeignService;
import com.zky.gulimall.product.service.*;
import com.zky.gulimall.product.vo.SecKillInfoVo;
import com.zky.gulimall.product.vo.SkuItemSaleAttrsVo;
import com.zky.gulimall.product.vo.SkuItemVo;
import com.zky.gulimall.product.vo.SpuItemAttrGroupVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zky.common.utils.PageUtils;
import com.zky.common.utils.Query;

import com.zky.gulimall.product.dao.SkuInfoDao;
import com.zky.gulimall.product.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService imagesService;
    @Autowired
    private SpuInfoDescService descService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private SkuSaleAttrValueService attrValueService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private SecKillFeignService feignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByContion(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();

        Object key = params.get("key");
        if (Objects.nonNull(key)) {
            String key1 = (String) key;
            queryWrapper.and(e -> {
                e.eq("sku_id", key1).or().like("sku_name", key1);
            });
        }

        Object catelogId = params.get("catelogId");
        if (Objects.nonNull(key)) {
            String catelogId1 = (String) catelogId;
            if (!"0".equalsIgnoreCase(catelogId1)) {
                queryWrapper.and(e -> {
                    e.eq("catalog_id", catelogId1);
                });
            }
        }

        Object brandId = params.get("brandId");
        if (Objects.nonNull(brandId)) {
            String brandId1 = (String) brandId;
            if (!"0".equalsIgnoreCase(brandId1)) {
                queryWrapper.and(e -> {
                    e.eq("brand_id", brandId1);
                });
            }
        }
        Object max = params.get("max");
        if (Objects.nonNull(max) && new BigDecimal((String) max).compareTo(new BigDecimal("0")) == 1) {
            Object min = params.get("min");
            if (Objects.nonNull(min)) {
                String min1 = (String) min;
                queryWrapper.ge("price", min1);
            }

            queryWrapper.le("price", (String) max);

        }


        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        return this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }

    @Override
    public SkuItemVo item(Long skuId) {
        SkuItemVo skuItemVo = new SkuItemVo();
        CompletableFuture<SkuInfoEntity> info = CompletableFuture.supplyAsync(() -> {
            //sku基本信息
            SkuInfoEntity result = getById(skuId);
            if (result != null) {
                skuItemVo.setSkuInfoEntity(result);
            }
            log.warn("info 处理结束：ThreadName:" + Thread.currentThread().getName());
            return result;
        }, executor);

        CompletableFuture<Void> saleAttrFuture = info.thenAcceptAsync(res -> {
            if (res != null) {
                //获取spu销售属性组合
                List<SkuItemSaleAttrsVo> saleAttrsVos = attrValueService.getSaleAttrsBySpuId(res.getSpuId());
                skuItemVo.setSaleAttr(saleAttrsVos);
            }
            log.warn("saleAttrFuture 处理结束：ThreadName:" + Thread.currentThread().getName());
        }, executor);

        CompletableFuture<Void> spuInfoDescFuture = info.thenAcceptAsync(res -> {
            if (res != null) {
                //获取spu销售属性介绍
                SpuInfoDescEntity infoDescEntity = descService.getById(res.getSpuId());
                skuItemVo.setDesc(infoDescEntity);
            }
            log.warn("spuInfoDescFuture 处理结束：ThreadName:" + Thread.currentThread().getName());
        }, executor);

        CompletableFuture<Void> spuItemAttrGroupFuture = info.thenAcceptAsync(res -> {
            if (res != null) {
                //获取spu的规则参数信息
                List<SpuItemAttrGroupVo> groupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
                skuItemVo.setGroupAttrs(groupVos);
            }
            log.warn("spuItemAttrGroupFuture 处理结束：ThreadName:" + Thread.currentThread().getName());

        }, executor);

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            //sku图片信息
            List<SkuImagesEntity> images = imagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(images);
            log.warn("imageFuture 处理结束：ThreadName:" + Thread.currentThread().getName());
        }, executor);

        CompletableFuture<Void> skuInfoQuery = CompletableFuture.runAsync(() -> {
            //当前sku是否参与秒杀优惠
            R skuSecKillInfo = feignService.getSkuSecKillInfo(skuId);
            if (skuSecKillInfo.isSuccess()) {
                String data = JSON.toJSONString(skuSecKillInfo.get("data"));
                SecKillInfoVo secKillInfoVo = JSON.parseObject(data, new TypeReference<SecKillInfoVo>() {
                });
                skuItemVo.setSecKillInfoVo(secKillInfoVo);

            }
        }, executor);

        //等待所有任务都完成再返回,info可不加
        try {
            CompletableFuture.allOf(saleAttrFuture, spuInfoDescFuture, spuItemAttrGroupFuture, imageFuture, skuInfoQuery).get();
            log.warn("CompletableFuture.allOf 处理结束：ThreadName:" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return skuItemVo;
    }

}